package com.example.wly.chapter4homework;

import android.Manifest;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {
    int page = 0; //显示页数
    int wordPerPages = 200;//每一页显示的字数
    int raw = 30;//行数
    int col = 50;//列数.
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String sdState = Environment.getExternalStorageState();
        textView = (TextView) findViewById(R.id.tv_text);
        Button btnRead = (Button) findViewById(R.id.btn_read);

        //将阅读器一些配置信息保存到文件，sharedPreference
        //获取实例
        //参数一文件名，不加扩展名
        //参数二文件的打开方式，私有方式，只有在应用程序内访问，其他应用不能访问
        SharedPreferences sp = getSharedPreferences("confug", MODE_PRIVATE);
        //写入
        //2.获取一个Editor编辑器
        SharedPreferences.Editor editor = sp.edit();
        //写入数据，写到editor中
        //键值对的方式进行写入
        editor.putInt("words", wordPerPages);
        //提交修改，将修改提交到文件中
        editor.commit();

        //读出数据
        //使用的sp和写入的sp是同一个
        //参数一关键字
        //参数二缺省值，关键字没有找到默认值的时候，用默认值
        sp.getInt("words", 100);
        Log.i("MainActivity", "onCreate:每页的字数=" + wordPerPages);


        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击按钮，读取文件内容
                //文件的位置strong/emulated/0/note.txt
                //中是字符
                //点击一次按钮，页数加一
                page++;

                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/note.txt";
                File file = new File(path);
                try {
                    FileInputStream in = new FileInputStream(file);//字节流
                    //字符流，进行转换，将字节流转换成字符流
                    //给字符流加缓冲流
                    //"utf-8"中文的编码格式，txt中包含中文，已知编码用的是"utf-8"
                    BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                    //读该页数据的时候，需要跳过前面所有页的数据
                    br.skip((page-1)*wordPerPages);
                    String line = "";//读出的数据保存在line中
                    for (int i=0; i<wordPerPages; i++)
                    {
                        int c = br.read(); //读一个字符，编码放在c中
                        line = line + (char)c;
                    }
//                    for (int i=0; i<10; i++)
//                    {
//                        line = line + br.readLine() + "\n";//读一行数据
//                    }
                    textView.setText(line);
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        //申请权限
        String[]perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if(!EasyPermissions.hasPermissions(this, perms))
        {
            EasyPermissions.requestPermissions(this, "write sd", 1, perms);
        }
        if(sdState.equals(Environment.MEDIA_MOUNTED))
        {
            Toast.makeText(this, "SD卡已激活", Toast.LENGTH_LONG).show();
            //sd卡的容量
            //获取sd卡的根目录，封装成File
            File dir = Environment.getExternalStorageDirectory();
            //获取文件的大小
            long totalspace = dir.getTotalSpace();//获取文件总容量
            long usespace = dir.getUsableSpace();//获取目录文件的可用容量
            Log.i("MainActivity", "sd卡总容量" + totalspace/1024/1024 + "M");
            Log.i("MainActivity", "sd卡可用容量" + usespace/1024/1024 + "M");
            //格式化大小
            String size = Formatter.formatFileSize(getApplicationContext(), totalspace);
            Log.i("MainActivity", "sd卡总容量" + size);
            //显示到文本框
            textView.setText("sd卡总容量：" + size + "\nsd卡可用容量：" + Formatter.formatFileSize(this, usespace));
            //文件的读写
            //写文件到sd卡
            //文件路径 Environment.getExternalStorageDirectory()，文件名'mysd.txt'
            //参数一路径，参数二文件名
            String path = dir.getAbsolutePath();


            File file = new File(path, "mysd.txt");

            Log.i("MainActivity", "文件的写入path" + path);
            try {
                FileOutputStream outputStream = new FileOutputStream(file);
                outputStream.write("write sd".getBytes());
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else {
            Toast.makeText(this, "SD卡没有被激活", Toast.LENGTH_LONG);
        }
    }
}
